import config from '../config/index'

export const request = (path, method, params) => {
  return new Promise((resolve, reject) => {
    let options = {
      url: `${config.baseurl}${path}`,
      method: method,
      header: {
        'Content-Type': 'application/json;charset=UTF-8'
      },
      data: params,
      success: (res) => {
        console.log(`${path}返回的参数-----------` ,res)
        wx.hideLoading()
        const {
          code
        } = res.data;
        if (code == 200) {
          resolve(res.data);
        } else if (code == 401) {
          wx.showToast({
            title: res.data.message || "用户认证失败，请重新登录",
            icon: 'none',
            duration: 2000
          })
          if (path !== "auth/oauth/mobile") {
            wx.clearStorage({
              success: (res) => {
                const app = getApp();
                app.globalData = {};
                wx.reLaunch({
                  url: '/pages/login/index',
                })
              },
            })
          }
          reject(res.data)
        } else {
          wx.showToast({
            title: res.data.message,
            icon: 'none',
            duration: 2000
          })
          reject(res.data);
        }
      },
      fail: (res) => {
        wx.hideLoading()
        wx.showToast({
          title: "哎呀，出错了",
          icon: 'none',
          duration: 2000
        })
        reject(res);
      }
    }
    if (path !== "auth/oauth/mobile" && path.indexOf("/openApi/") === -1) {
      if (wx.getStorageSync('token')) {
        options.header = {
          'Content-Type': 'application/json;charset=UTF-8',
          'Authorization': wx.getStorageSync('token')
        }
      }
    }
    console.log(`${path}请求接口入参-------`, options.data);
    wx.request(options);
  });
}
export const upload = (path, file) => {
  return new Promise((resolve, reject) => {
    // todo
    wx.uploadFile({
      url: `${config.baseurl}${path}`,
      name: 'file',
      filePath: file,
      header: {
        "Content-Type": "multipart/form-data"
      },
      formData: {},
      success: (res) => {
        // todo
        resolve(res);
      },
      fail: (res) => {
        reject(res);
      }
    });
  });
}